<template>
  <GroupPage
    :search-form-props="{
      keywordSearchData: [{ key: 'teamName', label: '班组名称' }],
      title: '排班计划',
    }"
    group-size="small"
    group-title="班组信息"
    :content-title="contentTitle"
    @search="onSearch"
  >
    <template #group>
      <SpinSkeleton v-show="tableLoading || tableData.length > 0" :loading="tableLoading">
        <div
          v-for="(el, i) in tableData"
          :key="el.id"
          class="py-2 px-4 mb-2 cursor-pointer hover-container"
          :class="[curIndex === i ? 'bg-opacity-10 bg-color-active' : 'bg-header']"
          @click="selectTeam(i)"
        >
          <div :class="[curIndex === i ? 'text-color-active' : 'text-color-main']">
            {{ el.teamName }}
          </div>
        </div>
      </SpinSkeleton>
      <SlEmpty v-show="!tableLoading && tableData.length === 0" :description="emptyText"></SlEmpty>
    </template>
    <template #content>
      <div class="flex-1 overflow-auto px-7">
        <SpinSkeleton :loading="loadingPlan">
          <a-calendar v-model:value="calendarValue" class="team-calendar">
            <template #dateCellRender="{ current }: { current: Dayjs }">
              <PlanDateItem
                :cur-team-index="curIndex"
                :current="current"
                :plan-data-object="planDataObject"
                @set-plan="handleSetPlan"
                @del-plan="handleDelPlan"
              />
            </template>
          </a-calendar>
        </SpinSkeleton>
      </div>
    </template>
  </GroupPage>
</template>
<script lang="ts" setup>
import { message } from "ant-design-vue";
import { computed, onMounted, ref, shallowRef, watch } from "vue";
import { useI18n } from "/@/locales/useI18n";

import { PlanItem, TeamItem, PlanType, PlanDataObj } from "/@/api/main/teamManage/models";
import { Api, delPlan, getPlan, setPlan } from "/@/api/main/teamManage";
import { useCURD } from "/@/hooks/useCURD";

import { useEmptyText } from "/@/hooks/useEmptyText";
import type { BodyCellOptions } from "/@/types/antd";
import dayjs from "dayjs";
import type { Dayjs } from "dayjs";
const { t } = useI18n();
/**
 * 班组
 */
async function onSearch(model) {
  await reloadTable({ model });
}
//班组CRUD数据定义
const { tableData, tableLoading, reloadTable, curd, searchModel } = useCURD<TeamItem>({
  getPageUrl: Api.teamsPage,
  pageSize: 999,
  loadOnMounted: true,
  loadFilter(data) {
    const teamData: TeamItem[] = [{ teamName: "全部" }];
    return teamData.concat(data);
  },
  onLoadSuccess() {
    curIndex.value = 0;
    loadPlanData(0);
  },
});

const { emptyText, modelForEmptyText } = useEmptyText();
watch(
  searchModel,
  (v) => {
    modelForEmptyText.value = v;
  },
  { deep: true }
);
//当前所选班组索引
const curIndex = ref(-1);
function selectTeam(i) {
  if (i === curIndex.value) return;
  curIndex.value = i;
  loadPlanData(i);
}
/**
 * plan
 */
const contentTitle = computed(() => {
  const team = tableData.value[curIndex.value];
  if (team) {
    return team.teamName + "排班日历";
  }
  return "排班日历";
});
const planData = ref<PlanItem[]>([]);
const planDataObject = ref<PlanDataObj>({});
async function loadPlanData(teamIndex: number) {
  const team = tableData.value[teamIndex];
  loadingPlan.value = true;
  const data = await getPlan({
    teamId: team.id,
    startDate: calendarValue.value.subtract(1, "month").startOf("month").format("YYYY-MM-DD"),
    endDate: calendarValue.value.add(1, "month").endOf("month").format("YYYY-MM-DD"),
  });
  if (data) {
    planData.value = data;
    const midObject: typeof planDataObject.value = {};
    data.forEach((el) => {
      const target = midObject[el.planDate];
      if (target) {
        target.push(el);
      } else {
        midObject[el.planDate] = [el];
      }
    });
    planDataObject.value = midObject;
  }
  loadingPlan.value = false;
}
const loadingPlan = ref(true);
const calendarValue = shallowRef<Dayjs>(dayjs());
let lastYearMonthStr = "";
watch(calendarValue, (v) => {
  const curYearMonthStr = v.format("YYYY-MM");
  if (lastYearMonthStr === curYearMonthStr) return;
  lastYearMonthStr = curYearMonthStr;
  loadPlanData(curIndex.value);
});
onMounted(() => {
  lastYearMonthStr = calendarValue.value.format("YYYY-MM");
});
async function handleSetPlan({ planType, current }: { planType: PlanType; current: Dayjs }) {
  const team = tableData.value[curIndex.value];
  if (team) {
    const re = await setPlan({ teamId: team.id as number, planDate: current.format("YYYY-MM-DD"), planType });
    if (re) {
      message.success("设置成功");
      loadPlanData(curIndex.value);
    }
  }
}
async function handleDelPlan(planId) {
  const re = await delPlan(planId);
  if (re) {
    message.success("删除成功");
    loadPlanData(curIndex.value);
  }
}
</script>
<style lang="less">
.team-calendar {
  .ant-picker-cell {
    vertical-align: top;
  }
  .ant-picker-calendar-header {
    justify-content: flex-start;
  }
  .ant-picker-calendar-mode-switch {
    display: none;
  }
  .ant-picker-calendar-date-content {
    height: auto !important;
    min-height: 86px;
  }
  .ant-picker-cell-inner {
    height: 100% !important;
  }
}
</style>
